<template>
    <d2-container>

        <el-dialog
                title="导出报表"
                :visible.sync="showExcel"
                width="400px">
            <el-form :inline="true"  >
                <el-form-item>
                    开始日期：
                <el-date-picker
                        v-model="start_time"
                        type="date"
                        placeholder="选择日期时间"
                        style='width: 150px'
                        >
                </el-date-picker>
            </el-form-item>

            <el-form-item >
                结束日期：
                <el-date-picker
                        v-model="end_time"
                        type="date"
                        placeholder="选择日期时间"
                        style='width:150px'
                        >
                </el-date-picker>
            </el-form-item>
            <el-form-item style='width: 150px;position: relative;margin-bottom: 10px;height: 50px'>
                <span style="position: absolute;left:0;width: 70px">类型：</span>
                <span style='position: absolute;left:73px;top:0;width: 150px'>
                        <el-select v-model="selectType" >

                                    <el-option
                                            v-for="item in filterType"
                                            :label="item.name"
                                            :value="item.value"
                                    ></el-option>
                                </el-select>
                </span>
                    </el-form-item>
                    
            </el-form>
            
            <div style="width: 100%;text-align: right">
            <el-button @click="showExcel = false">
                取消
            </el-button>
            <el-button @click="exportExcel" type='primary'>
                导出
            </el-button>
        </div>
            
        </el-dialog> 

        <el-dialog
                title="教材退款"
                :visible.sync="dialogVisible"
                width="400px">
            <el-form :inline="true" :model="stock_refund" ref="dataSearch">
                <el-form-item v-for=" refund_product in stock_refund" :key="refund_product.product.name">
                    商品名称:{{refund_product.product.name}}
                    <br>
                    商品id:{{refund_product.product._id}}
                    <br>
                    退款数量:
                    <el-input v-model="refund_product.count" placeholder="商品数量">
                    </el-input>
                </el-form-item>
            </el-form>
            <el-button @click="clickRefund">
                退款
            </el-button>
        </el-dialog>



            <el-dialog
                title="订单详情"
                :visible.sync="dialogVisible2"
                width="50%">

            <template>
                <div id="printMe">
                <el-table :data='productOrder.productOrder'>
                    <el-table-column
                            label="领取人">
                            <template slot-scope='scope'>
                                <div v-if="productOrder.method != '人工调整'">
                                    {{productOrder.student == '无' ? (productOrder.in == 1 ? productOrder.toSchool.name : productOrder.toSchool.name) :productOrder.student}}
                                </div>
                                <div v-else>人工调整</div>
                            </template>
                                
                    </el-table-column>
                    

                    <el-table-column label="订单详情">

                        <el-table-column
                                prop="product.name"
                                label="商品名称"
                                width="120">
                        </el-table-column>

                        <el-table-column
                                prop="amount"
                                label="购买数量"
                                width="120">
                        </el-table-column>

                        <el-table-column
                                prop="product.wholeSalePrice"
                                label="批发价格"
                                width="120">
                        </el-table-column>
                    <el-table-column
                                prop="product.sellingPrice"
                                label="销售价格"
                                width="120">
                        </el-table-column>
                        

                        <el-table-column
                               
                                label="购买时间"
                                width="120">
                                 <template slot-scope='scope'>
                                {{productOrder.date}}
                            </template>
                        </el-table-column>


                    </el-table-column>
                </el-table>
            
            
           
        </div>
            </template>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogVisible2 = false">关闭</el-button>
            </span>
        </el-dialog>


        <el-form :inline="true" :model="dataSearch" ref="dataSearch">

          <!--   <el-form-item label="领取学生" prop="student">
                <el-input v-model="dataSearch.student" placeholder="请输入学生姓名"></el-input>
            </el-form-item> -->

            <el-form-item label="经办人" prop="staff">
                <el-input v-model="dataSearch.staff" placeholder="请输入经办人姓名"></el-input>
            </el-form-item>

            <!-- <el-form-item label="商品名称" prop="name">
                <el-input v-model="dataSearch.name" placeholder="请输入商品名称"></el-input>
            </el-form-item> -->
            <el-form-item label="商品名称" prop="name">
                <el-input v-model="dataSearch.name" placeholder="请输入商品名称"></el-input>
            </el-form-item>

            <el-form-item label="进出库" prop="status">
                <el-select v-model="inout" clearable placeholder="进出库" >
                    <el-option
                            v-for="item in stockStatus"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                    ></el-option>
                </el-select>
            </el-form-item>
            <div style="display: block">
                <el-form-item>
                    开始日期：
                <el-date-picker
                        v-model="dataSearch.start_time"
                        type="date"
                        placeholder="选择日期时间"
                        style='width: 150px'
                        >
                </el-date-picker>
            </el-form-item>

            <el-form-item >
                结束日期：
                <el-date-picker
                        v-model="dataSearch.end_time"
                        type="date"
                        placeholder="选择日期时间"
                        style='width:150px'
                        >
                </el-date-picker>
            </el-form-item>
             <el-form-item>
                <el-button type="primary" @click="formSubmit">
                    <d2-icon name="search"/>
                    查询
                </el-button>
            </el-form-item>

            <el-form-item>
                <el-button @click="formReset">
                    <d2-icon name="refresh"/>
                    重置
                </el-button>
            </el-form-item>
            <br>
        </div>

           

           

            <el-form-item>
                <a href="#/product-new?productIn=1">
                    <el-button type="primary" style="float:right" icon="el-icon-plus">出入库调整</el-button>
                </a>
            </el-form-item>
             <el-form-item>
                    <el-button type="primary" style="float:right" @click='showExcel = true'>导出记录</el-button>

            </el-form-item>
        </el-form>

        <el-table :data="StockList" border style="width: 100%">
            <el-table-column prop="productName" label="商品名称"></el-table-column>
            <el-table-column prop="staff" label="经办人"></el-table-column>
            <el-table-column prop="student" label="领取学生"></el-table-column>
            <el-table-column prop="toSchool.name" label="(进库)校区"></el-table-column>
            <el-table-column prop="school.name" label="(出库)校区"></el-table-column>

            <!--      <el-table-column prop="price" label="金额"></el-table-column>-->
            <el-table-column prop="method" label="类型"></el-table-column>
            <el-table-column prop="type" label="状态"></el-table-column>
                         <el-table-column
                                prop="memoIn"
                                label="备注"
                                width="150">
                        </el-table-column>
             <el-table-column
                                prop="date"
                                label="日期"
                                width="120">
                        </el-table-column>
                  <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
            <!--&lt;!&ndash;          <el-button @click="handleRefundRefund(scope.row)" type="text" size="small">退款</el-button>&ndash;&gt;-->
            <!--&lt;!&ndash;          <el-button @click="deleteClick(scope.row)" type="text" size="small">删除</el-button>&ndash;&gt;-->
                    </template>
                  </el-table-column>
        </el-table>
        <el-pagination
                background
                layout="total,sizes,prev, pager, next,jumper"
                :page-size="pageSize"
                :current-page="currentPage"
                :total="total"
                @current-change="handleCurrentChange"
                @size-change="handlerSizeChange"
                @next-click="handleNextPage"
                @prev-click="handlePrevClick"
        ></el-pagination>
    </d2-container>
</template>

<script>
    import request from "@/plugin/axios";
    import {mapState} from "vuex";
    import formatTime from '@/libs/util.formatTime.js'
        import excel from "@/libs/util.excel"

    export default {
        data() {
            return {
                StockList: [],
                categoryList: [],
                showExcel :false,
                total: 0,
                pageSize: 20,
                currentPage: 1,
                dialogVisible2 : false,
                start_time : undefined,
                end_time : undefined,
                selectType : undefined,
                filterType : [{name:'全部',value:'all'},{name:'学生',value:'student'},{name:'校区',value:'school'}],
                stockStatus: [
                    {
                        label: '进库',
                        value: 1
                    },
                    {
                        label: '出库',
                        value: 0
                    }
                ],
                dataSearch: {
                    staff: "",
                    student: "",
                    status: "",
                    name:undefined,
                    start_time : undefined,
                    end_time : undefined
                },
                productOrder : {},
                refund_id: undefined,
                dialogVisible: false,
                stock_refund: undefined,
                refund_school: undefined,
                school: undefined,
                inout : undefined
            };
        },
        computed: {
            ...mapState('d2admin/user', ['info']),
        },
        methods: {

            getStockOne(_id) {
                request({
                    url: "/productOrder/getWarehouseOne",
                    method: "post",
                    data: {_id: _id}
                }).then(res => {
                    this.stock_refund = res.data.products
                });

            },

            handleRefundRefund(e) {
                this.dialogVisible = true
                this.refund_id = e._id
                this.refund_school = e.school._id
                this.getStockOne(this.refund_id)
            },

            clickRefund() {

                request({
                    url: "/productOrder/deleteProductOrder",
                    method: "post",
                    data: {
                        _id: this.refund_id,
                        refund_school: this.refund_school,
                        stock_refund: this.stock_refund
                    }
                }).then(res => {

                    if (res.code == 200) {
                        this.$message({
                            message: "退款成功"
                        });
                        this.dialogVisible = false
                        this.getStockList(1, this.pageSize);
                    }
                });
            },



            formSubmit() {
                this.getStockList(1, this.pageSize);
            },
            formReset() {
                this.$refs.dataSearch.resetFields();
            },
            handleClick(e) {
                console.log(e,'sd')
                this.dialogVisible2 = true
                this.productOrder = e
            },
            deleteClick(e) {
                this.$confirm("此操作将删除该商品, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        request({
                            url: "/product/deleteProduct",
                            method: "post",
                            data: {id: e._id}
                        }).then(res => {
                            if (res.code == 200) {
                                this.$message({
                                    message: "删除成功"
                                });
                                this.getProductList(1, this.pageSize);
                            }
                        });
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除"
                        });
                    });
            },

            handleCurrentChange(e) {
                this.getStockList(e, this.pageSize);
            },
            handlerSizeChange(e) {
                this.pageSize = e;
                this.getStockList(1, this.pageSize);
            },
            handleNextPage(e) {
                this.getStockList(e, this.pageSize);
            },
            handlePrevClick(e) {
                this.getStockList(e, this.pageSize);
            },

           

            getStockList(page, pageSize) {
                let data = this.dataSearch;
                (data.page = page), (data.pageSize = pageSize);
                this.school = this.info.school.map(value => value._id);
                data.school = this.school;
                if (this.headquarter){
                    data.headquarter = 1
                }
                if (this.inout != undefined){
                    data.type = this.inout
                }
                request({
                    url: "/productOrder/getWarehouseList",
                    method: "post",
                    data
                }).then(res => {
                    // console.log(res)
                    this.StockList = res.data.product;
                    let price = 0
                    this.StockList.forEach((product, index) => {
                        this.StockList[index].productName = product.productOrder.map((value => `${value.product.name} x ${Math.abs(value.amount)}`)).join(',')

                        this.StockList[index].date = formatTime.formatTime(new Date(this.StockList[index].createdAt))
                        this.StockList[index].price = this.StockList[index].total - this.StockList[index].discount
                        if (product.agent) {
                            this.StockList[index].staff = product.agent.name
                        }

                        this.StockList[index].school = product.school

                        if (product.student) {
                            this.StockList[index].student = product.student.name
                        }
                        else{
                            this.StockList[index].student = '无'
                        }
                        if (product.adjust == 1){
                            if (product.in == 0){
                                this.StockList[index].type = '出库'
                            }
                            else{
                                this.StockList[index].type = '入库'
                            }

                            this.StockList[index].method = '人工调整'
                            if (product.request != undefined){
                                this.StockList[index].method = '采购入库'
                                let temp = product.toSchool
                                let jj = product.school
                                // let temp = this.StockList[index]
                                this.StockList[index].school = temp
                                this.StockList[index].toSchool = jj
                            }
                        }
                        else{
                            this.StockList[index].type = '出库'
                            if (product.toSchool != undefined){
                                if (product.in == 0){
                                    this.StockList[index].method = '校区出售'
                                }
                                else{
                                    this.StockList[index].method = '校区购买'
                                }
                                
                            }
                            else{
                                this.StockList[index].method = '正常出售'
                            }
                            
                        }
                    })

                    this.total = res.data.count;
                    // 返回数据
                });
            },

            getCategoryList(pageSize) {
                request({
                    url: "/productCategory/getProductCategoryList",
                    method: "post",
                    data: {pageSize: pageSize}
                }).then(res => {
                    this.categoryList = res.data.productCategory;
                    console.log(this.categoryList,'thiis')
                });
            },
            getSchoolList() {
                request({
                    url: "/school/getSchoolList",
                    method: "post",
                }).then(res => {
                    this.schoolList = res.data.school;
                    // 返回数据
                });
            },

            exportExcel(){
                let data = {}
                if (new Date(this.start_time) >new Date(this.end_time)){
                    this.$message('开始时间不能大于结束时间')
                    return false
                }
                data.start_time = this.start_time
                data.end_time = this.end_time
                data.type = this.selectType
                data.school = this.school
                request({
                    url: "/product/exportProductDetail",
                    method: "post",
                    data: data
                }).then(res => {
                   if (res.code == 200){
                    excel.export(res.data.columns,res.data.data, this.info.school[0].name + '商品出入库记录')
                   }
                });

            },
            load(){
                this.getStockList(1, this.pageSize);
            this.getCategoryList(-1);
            this.school = this.info.school[0]._id
            this.headquarter = (this.info.school[0].headquarter == 1) || (this.info.school[0].headquarter == 2)
            this.start_time = new Date(new Date().getTime() - 3600000 * 24 * 30)
            this.end_time = new Date()
            this.selectType = 'all'
            }
        },
         beforeRouteEnter(to, from, next) {
            if (to.meta.refresh == 'a'){
                to.meta.refresh = undefined
                next(v=>{
                v.load()
                })
            }
            else{
                next()
            }
        },
        created() {
            
            this.load()
        }
    };
</script>
